package com.zhongwang.mms.module.allocation.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.allocation.dao.AllocationOrderDao;
import com.zhongwang.mms.module.allocation.dao.AllocationOrderDetailDao;
import com.zhongwang.mms.module.allocation.model.AllocationOrderModel;
import com.zhongwang.mms.module.basic.dao.TCostDao;
import com.zhongwang.mms.module.basic.dao.TDeptDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.half.dao.HOrderDao;
import com.zhongwang.mms.module.half.dao.HOrderDetailDao;
import com.zhongwang.mms.module.half.model.HOrderDetailModel;
import com.zhongwang.mms.module.half.service.CreateOrderCodeService;
import com.zhongwang.mms.module.half.service.HInventoryService;
import com.zhongwang.mms.module.material.model.MOrderDetailModel;
import com.zhongwang.mms.module.material.model.MOrderInsertModel;
import com.zhongwang.mms.module.material.service.MOrderService;
import com.zhongwang.mms.module.purchase.constant.PurchaseConstant;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.dao.PurPOrderDao;
import com.zhongwang.mms.module.purchase.model.POrderDetail;
import com.zhongwang.mms.module.purchase.model.POutOrder;
import com.zhongwang.mms.module.purchase.service.PurWarInManageService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:调拨入库
 * @author: th
 * @time: 2020/8/22 8:34
 */
@Slf4j
@Service
public class AllocationInWarService {

    @Autowired
    private AllocationOrderDetailDao allocationOrderDetailDao;
    @Autowired
    private AllocationOrderDao allocationOrderDao;
    @Autowired
    private PurPOrderDao purPOrderDao;
    @Autowired
    private PurWarInManageService purWarInManageService;
    @Autowired
    private LogService logService;
    @Autowired
    private TCostDao tCostDao;
    @Autowired
    private BoardService boardService;
    @Autowired
    private TWarehouseInfoDao tWarehouseInfoDao;
    @Autowired
    private com.zhongwang.mms.module.purchase.dao.PurPOrderDetailDao purPOrderDetailDao;
    @Autowired
    private PurPInventoryDao purPInventoryDao;
    @Autowired
    private MOrderService mOrderService;
    @Autowired
    private CreateOrderCodeService createOrderCodeService;
    @Autowired
    private HOrderDao hOrderDao;
    @Autowired
    private TDeptDao tDeptDao;
    @Autowired
    private HOrderDetailDao hOrderDetailDao;
    @Autowired
    private HInventoryService hInventoryService;

    /***
     * 修改入库数量
     * @param param
     * @return
     */
    public JsonResult updateAllocationInWarNum(AllocationOrderModel param) {

        allocationOrderDetailDao.updateByPrimaryKeySelective(param);
        return JsonResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveAllocationInWar(AllocationOrderModel param) {
        JsonResult jsonResult = new JsonResult();
        List<String> result = new ArrayList<>();
        //获取调拨主单信息
        AllocationOrderModel allocationOrder = allocationOrderDao.selectAllByPrimaryKey(param.getOdrId());
        //获取调拨明细列表
        List<POrderDetail> list = allocationOrderDetailDao.selectPurInDetailByOdrId(param.getOdrId());
        AllocationOrder allocationOrder1 = new AllocationOrder();
        if(allocationOrder.getOdrType() == 1){
            POutOrder pOutOrder = new POutOrder();
            List<POrderDetail> pOrderDetails = allocationOrderDetailDao.selectPurInDetailByOdrId(param.getOdrId());
            pOutOrder.setInsertData(pOrderDetails);
            POrder pOrder = new POrder();
            pOrder.setOdrCode(purWarInManageService.getOrderCode(PurchaseConstant.PRK));
            pOrder.setOdrType(1);
            pOrder.setOdrRedFlag(0);
            pOrder.setOdrDate(param.getOdrDate());
            pOrder.setOdrRemark(param.getOdrRemark());
            pOrder.setOdrTakePerson(param.getOdrTakePerson());
            pOrder.setOdrTakeWorkshopId(param.getOdrDept());
            pOrder.setOdrReqFlag(1);
            pOrder.setOdrChangeFlag(0);
            pOrder.setOdrMakeDate(new Date());
            pOrder.setOdrMakePersonId(ShiroUtils.getUser().getId());
            pOrder.setOdrDept(param.getOdrDept());
            pOrder.setOdrOutType(8);
            pOrder.setOdrRepId(allocationOrder.getOdrCode());
            purPOrderDao.insert(pOrder);
            allocationOrder1.setOdrOutStatus(3);
            allocationOrder1.setOdrId(param.getOdrId());
            allocationOrderDao.updateByPrimaryKeySelective(allocationOrder1);

            Integer odrId = pOrder.getOdrId();
            try {
                //创建明细单
                for (com.zhongwang.mms.module.purchase.model.POrderDetail pOrderDetailModel : list) {
                    if (null!=pOrderDetailModel.getOdaTrackCode() && pOrderDetailModel.getOdaTrackCode().trim().replace("\\s", "").replace("\n", "").equals("000000")) {
                        pOrderDetailModel.setOdaTrackCode("");
                    }
                    com.zhongwang.mms.gen.entity.POrderDetail pOrderDetail = new com.zhongwang.mms.gen.entity.POrderDetail();
                    pOrderDetail.setOdaType(1);
                    pOrderDetail.setOdaOdrId(odrId);
                    pOrderDetail.setOdaRedFlag(0);
                    pOrderDetail.setOdaMatCode(pOrderDetailModel.getOdaMatCode());
                    pOrderDetail.setOdaSapCode(pOrderDetailModel.getOdaSapCode());
                    pOrderDetail.setOdaMatDesc(pOrderDetailModel.getOdaMatDesc());
                    pOrderDetail.setOdaNum(pOrderDetailModel.getOdaNum());
                    pOrderDetail.setOdaNumUnit(pOrderDetailModel.getOdaNumUnit());
                    pOrderDetail.setOdaTotalPrice(pOrderDetailModel.getOdaNum()*pOrderDetailModel.getOdaNumPrice());
                    pOrderDetail.setOdaNumPrice(pOrderDetailModel.getOdaNumPrice());
                    pOrderDetail.setOdaTrackCode(pOrderDetailModel.getOdaTrackCode());
                    pOrderDetail.setOdaProName(pOrderDetailModel.getOdaProName());
                    pOrderDetail.setOdaProCode(boardService.projectCodeHandle(pOrderDetailModel.getOdaProCode()));
                    pOrderDetail.setOdaWhiId(pOrderDetailModel.getOdaInWhiId());
                    pOrderDetail.setOdaPosition(pOrderDetailModel.getOdaPosition());
                    if (pOrderDetailModel.getOdaItyStockType().equals("项目在库")) {
                        pOrderDetail.setOdaStockType(2);
                    } else if (pOrderDetailModel.getOdaItyStockType().equals("库存在库")) {
                        pOrderDetail.setOdaStockType(1);
                    }
                    if (pOrderDetailModel.getOdaBookkeepingDate() != null && !pOrderDetailModel.getOdaBookkeepingDate().equals("")) {
                        pOrderDetail.setOdaBookkeepingDate(new SimpleDateFormat("yyyy-MM-dd").parse(pOrderDetailModel.getOdaBookkeepingDate().replace('/', '-')));
                    }

                    pOrderDetail.setOdaSpec(pOrderDetailModel.getOdaSpec());
                    pOrderDetail.setOdaBrand(pOrderDetailModel.getOdaBrand());
                    purPOrderDetailDao.insert(pOrderDetail);
                    //检测库存表中是否有相同的数据
                    PInventory pInventory = new PInventory();
                    pInventory.setItyMatCode(pOrderDetail.getOdaMatCode());
                    pInventory.setItySapCode(pOrderDetail.getOdaSapCode());
                    pInventory.setItyMatDesc(pOrderDetail.getOdaMatDesc());
                    pInventory.setItyNum(pOrderDetail.getOdaNum());
                    pInventory.setItyAvaNum(pOrderDetail.getOdaNum());
                    pInventory.setItyNumUnit(pOrderDetail.getOdaNumUnit());
                    pInventory.setItyPrice(pOrderDetail.getOdaNumPrice());
                    pInventory.setItyTrackCode(pOrderDetail.getOdaTrackCode());
                    pInventory.setItyProName(pOrderDetail.getOdaProName());
                    pInventory.setItyProCode(pOrderDetail.getOdaProCode());
                    pInventory.setItyWhiId(pOrderDetail.getOdaWhiId());
                    pInventory.setItyPosition(pOrderDetail.getOdaPosition());
                    pInventory.setItyRemark(pOrderDetail.getOdaSpec());
                    pInventory.setItyRowNo(pOrderDetail.getOdaId());
                    if (tCostDao.getTCostByCosProCode(pOrderDetail.getOdaProCode()) != null) {
                        pInventory.setItyStockType(1);
                    } else if (pOrderDetailModel.getOdaItyStockType().equals("项目在库")) {
                        pInventory.setItyStockType(2);
                    } else if (pOrderDetailModel.getOdaItyStockType().equals("库存在库")) {
                        pInventory.setItyStockType(1);
                    }
                    pInventory.setItyBookkeepingDate(pOrderDetail.getOdaBookkeepingDate());
                    //如果检测结果为0则侧入数据，否则合并数据
                    //物料编码+行号（入库明细id）+项目文本+项目编码+库存地为批次字段，批次字段相同时，入库时要做物料合并，数量相加，
                    PInventory pInventoryObj = purPInventoryDao.findInventoryByParam(pInventory);
                    //如果库存表没有此数据
                    if (null == pInventoryObj) {
                        //往库存表插入数据
                        purPInventoryDao.insertSelective(pInventory);
                    } else {
                        ///如果库存表有此数据，开始进行合并数据：合并改规则如下
                        //总数量
                        Double totalNum = pInventory.getItyNum() + pInventoryObj.getItyNum();
                        //单价=总金额之和/总数量，
                        Double price = (pInventory.getItyAmount() + pInventoryObj.getItyAmount()) / totalNum;
                        //总金额=计算后的单价*数量,由数据库自动计算
                        //单价
                        pInventoryObj.setItyPrice(price);
                        //总数量
                        pInventoryObj.setItyNum(totalNum);
                        purPInventoryDao.updateByPrimaryKeySelective(pInventoryObj);
                    }
                }
                result.add("单据保存成功！");
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setData(result);
                //记录操作日志
                logService.saveLog("调拨入库-入库", "入库单据编码：" + pOrder.getOdrCode());
            } catch (Exception ex) {
                ex.printStackTrace();
                //记录异常错误日志信息
                log.error("【调拨入库-异常日志】:异常入库单编码：" + pOrder.getOdrCode() + "{" + ex.getMessage() + "}");
                result.add("单据保存失败！");
                jsonResult.setData(result);
            }
            return jsonResult;
        }else if(allocationOrder.getOdrType() == 2){
            MOrderInsertModel mOrderInsertModel = new MOrderInsertModel();
            List<MOrderDetailModel> mOrderDetailModels = allocationOrderDetailDao.selectMatDetailByOdrId(param.getOdrId());
            mOrderInsertModel.setInsertData(mOrderDetailModels);
            MOrder mOrder = new MOrder();
            mOrder.setOdrDate(param.getOdrDate());
            mOrder.setOdrRemark(param.getOdrRemark());
            mOrder.setOdrTakePerson(param.getOdrTakePerson());
            mOrder.setOdrType(6);
            mOrder.setOdrRepId(allocationOrder.getOdrCode());
            mOrder.setOdrWhiId(allocationOrder.getOdrInWhiId());
            //mOrder.setOdrTakeWorkshop(tDeptDao.selectByPrimaryKey(param.getOdrDept()).getDepName());
            mOrderInsertModel.setFormData(mOrder);
            String msg = mOrderService.saveInOrderModel(mOrderInsertModel);
            if (!msg.contains("保存失败")) {
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                allocationOrder1.setOdrOutStatus(3);
                allocationOrder1.setOdrId(param.getOdrId());
                allocationOrderDao.updateByPrimaryKeySelective(allocationOrder1);
            }
            jsonResult.setMsg(msg);

            return jsonResult;
        }else {
            // 保存入库单主单信息
            HOrder hOrderForm = new HOrder();
            // 获取登入用户实体
            User user = ShiroUtils.getUser();

            hOrderForm.setOdrType(1);//入库
            hOrderForm.setOdrStatus(1);//调拨
            hOrderForm.setOdrDate(new Date());//制单时间
            hOrderForm.setOdrCode(createOrderCodeService.getInOrderCode());//单据号
            hOrderForm.setOdrTakePerson(user.getName());//制单人
            hOrderForm.setOdrRedFlag(0); //红冲标识
            hOrderForm.setOdrItyFlag(1); //1蓝单2红单
            hOrderForm.setOdrChecker(param.getOdrTakePerson());
            hOrderForm.setOdrSummary(param.getOdrRemark());
            hOrderForm.setOdrMakeDate(param.getOdrDate());
            hOrderForm.setOdrOutType(3);
            hOrderForm.setOdrRepId(allocationOrder.getOdrCode());
            //hOrderForm.setOdrDept(tDeptDao.selectByPrimaryKey(param.getOdrDept()).getDepName());

            //保存主单信息
            hOrderDao.insert(hOrderForm);

            List<HOrderDetailModel> hOrderDetailModels = allocationOrderDetailDao.selectHalDetailByOdrId(param.getOdrId());
            for (HOrderDetailModel hOrderDetailModel : hOrderDetailModels){
                //获取主单ID
                hOrderDetailModel.setOdrId(hOrderForm.getOdrId());
                //获取仓库
                hOrderDetailModel.setOdaWhiId(hOrderDetailModel.getOdaWhiId());
                hOrderDetailModel.setOdaNum(hOrderDetailModel.getOdaAvaNum());
                //物料分类
                hOrderDetailModel.setOdaMatType(2);//1是外购件、2是外协件、3是制作件
                //物料编码
                hOrderDetailModel.setOdaMatCode("1111111111");
                //红冲标识
                hOrderDetailModel.setOdaRedFlag(0);

                hOrderDetailModel.setOdaAmount(hOrderDetailModel.getOdaNum()*hOrderDetailModel.getOdaPrice());

                hOrderDetailModel.setOdaOdrId(hOrderForm.getOdrId());

                hOrderDetailDao.insert(hOrderDetailModel);
                //保存库存信息
                hInventoryService.saveHInventory(hOrderDetailModel);
            }
            //记录操作日志
            logService.saveLog("调拨入库-入库", "入库单据编码：" + hOrderForm.getOdrCode());
            jsonResult.setData("单据保存成功！");
            allocationOrder1.setOdrOutStatus(3);
            allocationOrder1.setOdrId(param.getOdrId());
            allocationOrderDao.updateByPrimaryKeySelective(allocationOrder1);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            return jsonResult;
        }
    }
}
